package fun.codefarmer.pm.utils.fileUtil;
import com.sun.image.codec.jpeg.JPEGCodec;
import com.sun.image.codec.jpeg.JPEGEncodeParam;
import com.sun.image.codec.jpeg.JPEGImageEncoder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;

public class PictureUtil {
    private final static Logger logger = LoggerFactory.getLogger(PictureUtil.class);

    /**
     * @param originalFilePath          原图片所在的文件夹路径
     * @param originalFileObject        原图片路径
     * @param originalFileExtensionName 原图片扩展名
     * @param originalFileName          原图片名
     * @param percent             压缩百分比
     */
    public static void Tosmallerpic(String originalFilePath, File originalFileObject, String originalFileExtensionName, String originalFileName, float percent) {
        Image src;
        try {
            src = javax.imageio.ImageIO.read(originalFileObject); //构造Image对象
            String img_midname = originalFilePath+ "/"+ originalFileName.substring(0, originalFileName.indexOf(".")) + originalFileExtensionName;
            BufferedImage tag = new BufferedImage(src.getWidth(null), src.getHeight(null), BufferedImage.TYPE_INT_RGB);
            //tag.getGraphics().drawImage(src,0,0,new_w,new_h,null); //绘制缩小后的图
            tag.getGraphics().drawImage(src.getScaledInstance(src.getWidth(null), src.getHeight(null), Image.SCALE_SMOOTH), 0, 0, null);
            FileOutputStream newImage = new FileOutputStream(img_midname); //输出到文件流
            JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(newImage);
            JPEGEncodeParam jep = JPEGCodec.getDefaultJPEGEncodeParam(tag);
            /* 压缩质量 */
            jep.setQuality(percent, true);
            encoder.encode(tag, jep);
            //encoder.encode(tag); //近JPEG编码
            newImage.close();
        } catch (IOException ex) {
            logger.error("图片压缩失败", ex);
        }
    }
}
